// tradeList.js
const app = getApp()
import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'
import { formatPrice } from '../../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    channel: '',
    loading: false,
    page: 1,
    tradeStatus: 0,
    hasComment: 0,
    orderArr: [],
    isDelete: false,
    requestFlag: false,
    noMore: false,
    noData: false,
    seller_url: '',
    errorTradeMsg:[],     // 订单提示消息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let channel = options.channel || 'wx_xcx'
    let systemInfo = {}

    try {
      systemInfo = wx.getSystemInfoSync()
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      winWidth: systemInfo.windowWidth,
      winHeight: systemInfo.windowHeight,
      channel,
      tradeStatus: options.tradeStatus
    })
  },

    onShow() {
        if (app.toLogin()) {
            this.getOrderData(this.data.tradeStatus);
            return false
        }
    },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.tradeStatus == 5) {
      this.getOrderData(this.data.tradeStatus, this.data.hasComment)
    } else {
      this.getOrderData(this.data.tradeStatus)
    }
  },

  changeTab: function (e) {
    let tradeStatus = e.currentTarget.id
    let hasComment = 0

    this.setData({
      page: 1,
      tradeStatus: tradeStatus,
      hasComment: hasComment,
    })

    if (tradeStatus != 8) {
      this.setData({
        loading: false
      })
    } else {
      this.setData({
        loading: true
      })
    }
    if (tradeStatus == 5) {
      this.tabOrderData(tradeStatus, hasComment)
    } else if (tradeStatus != 8) {
      this.tabOrderData(tradeStatus)
    }
  },

  toValuation: function (e) {
    let tradeNo = e.currentTarget.id
    let url = '../valuation/valuation?trade_no=' + tradeNo + '&channel=' + this.data.channel

    wx.navigateTo({
      url: url,
    })
  },

  toLogistic: function (e) {
    let tradeNo = e.currentTarget.id
    let url = '../logisticsInfo/logisticsInfo?trade_no=' + tradeNo + '&channel=' + this.data.channel

    wx.navigateTo({
      url: url,
    })
  },

  toOrderDetail: function (e) {
    let tradeNo = e.currentTarget.id
    let url = '../tradeDetail/tradeDetail?trade_no=' + tradeNo + '&channel=' + this.data.channel

    wx.navigateTo({
      url: url,
    })
  },

  toDelete: function (e) {
    if (this.data.requestFlag) return false

    this.data.requestFlag = true

    let tradeNo = e.currentTarget.id
    let index = e.currentTarget.dataset.index
    let options = {
      url: requestApi.orderDeleteUrl,
      method: 'POST',
      data: {
        'trade_no': tradeNo,
        'channel': this.data.channel,
      },
    }

    this.data.orderArr.splice(index, 1)

    app.request(
      options,
      (data) => {
        wx.showToast({
          title: '删除成功',
        })

        this.setData({
          orderArr: this.data.orderArr,
        })
      },
      (error) => {
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })
      }, () => {
        this.data.requestFlag = false
      })
  },

  getOrderData: function (tradeStatus, hasComment) {
    if (this.data.noMore) return false

    if (this.data.requestFlag) return false

    this.data.requestFlag = true

    let param
    let page = this.data.page
    let count = 20
    let start = (page - 1) * count

    if (hasComment) {
      param = {
        start: start,
        count: count,
        trade_status: tradeStatus,
        has_comment: hasComment,
        channel: this.data.channel,
      }
    } else if (tradeStatus) {
      param = {
        start: start,
        count: count,
        trade_status: tradeStatus,
        channel: this.data.channel,
      }
    } else {
      param = {
        start: start,
        count: count,
        channel: this.data.channel,
      }
    }

    app.request({
      url: requestApi.orderListUrl,
      data: param,
    }, (res) => {
      let noMore, noData
      let currArr = this.data.orderArr
      let data = this.handleTradeListData(res)
      let orderArr = currArr.concat(data.original.data.item_list)
      let errorTradeMsg = data.original.error_trade_msg ? data.original.error_trade_msg : []

      if (data.original.data.total == 0 && page == 1) {
        noData = true
      }

      if (data.original.data.total < count) {
        noMore = true
      } else {
        noMore = false
      }

      this.setData({
        tradeStatus: this.data.tradeStatus,
        loading: true,
        orderArr: orderArr,
        page: this.data.page + 1,
        noMore: noMore,
        noData: noData,
        errorTradeMsg,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      this.data.requestFlag = false
    })
  },

  tabOrderData: function (tradeStatus, hasComment) {
    if (this.data.requestFlag) return false

    this.data.requestFlag = true

    let param
    let count = 20
    let start = 0

    if (hasComment) {
      param = {
        start: start,
        count: count,
        trade_status: tradeStatus,
        has_comment: hasComment,
        channel: this.data.channel,
      }
    } else if (tradeStatus) {
      param = {
        start: start,
        count: count,
        trade_status: tradeStatus,
        channel: this.data.channel,
      }
    } else {
      param = {
        start: start,
        count: count,
        channel: this.data.channel,
      }
    }

    app.request({
      url: requestApi.orderListUrl,
      data: param,
    }, (res) => {
      let data = this.handleTradeListData(res)
      let orderArr = data.original.data.item_list
      let noData

      if (data.original.data.total == 0) {
        noData = true
      } else {
        noData = false
      }
      this.setData({
        loading: true,
        orderArr: orderArr,
        page: this.data.page + 1,
        noData: noData,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      this.data.requestFlag = false
    })
  },
  // 处理接口返回的订单列表数据
  handleTradeListData: function (data) {
    if (data.original && data.original.data.total) {
      let d = data.original.data.item_list;
      for (let i = 0; i < d.length; i++) {
          if (d[i].type == 194) {
              let item = d[i].data;

              item['product_cover_image']['new_path'] = item['product_cover_image'] && item['product_cover_image']['path'] ? formatImage.cdnImage(item['product_cover_image']['path'], formatImage.THUMBNAIL_S) : '';
              item['new_pay_price'] = item['pay_price'] ? '￥' + formatPrice(item['pay_price'] / 100) : ''
              item['new_seller_avatar_uri'] = item['seller_avatar_uri'] ? formatImage.cdnImage(item['seller_avatar_uri'], formatImage.THUMBNAIL_XS) : ''
              item['trade_status_cn'] = item['trade_status'] ? this.getTradeStatusCn(item['trade_status'], item['has_comment']) : ''
      
              if (item['trade_status'] == 7 || item['trade_status'] == 9) {
                item['is_grey'] = true
              } else {
                item['is_grey'] = false
              }
      
              item['group_icon'] || (item['group_icon'] = {})
              item['group_icon']['full_path'] = item['group_icon']['path'] ? formatImage.cdnImage(item['group_icon']['path']) : ''
          }
      }
      data.original.data.item_list = d
    }
    return data
  },
  getTradeStatusCn(status, comment) {
    switch (status) {
      case -1:
        return '交易完成';
      case 1:
        return '等待商家接单';
      case 2:
        return '等待您付款';
      case 3:
        return '等待商家发货';
      case 4:
        return '等待您签收';
      case 5:
        return comment == 0 ? '等待您评价' : '评价完成';
      case 6:
        return '商家拒绝接单';
      case 7:
        return '商家待发货';
      case 8:
        return '退款成功';
      case 9:
        return '买家取消订单';
      case 10:
        return '订单已关闭';
      case 11:
        return '退款中';
    }
  },

  //店铺详情
  shopTap: function (e) {
    let seller_uid = e.currentTarget.dataset.id
    
    app.request({
        url: requestApi.isFlashStore,
        login: false,
        data: {
            seller_uid: seller_uid
        },
    }, (data) => {
        if(data.original.data.is_flash) {
            wx.navigateTo({
                url: '/pages/shop/shop?shop_id='+ data.original.data.id + '&seller_uid=' + seller_uid,
            })
        } else {
          wx.navigateTo({
            url: '../../store/store?seller_uid=' + seller_uid,
          })
        }
    }, (error) => {
        wx.showModal({
            title: '提示',
            showCancel: false,
            content: error,
        })
    })
  },
})